package com.mojian.service;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import com.mojian.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService{

    private final FileStorageService fileStorageService;

    @Override
    public String upload(MultipartFile file) {

        //获取文件名和后缀
        String originalFilename = file.getOriginalFilename();
        String fileName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //1 在文件名称里面添加随机唯一的值
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String datePath = new DateTime().toString("yyyy/MM/dd/");
        // yuy76t5rew01.jpg
        fileName = uuid + fileName;
        FileInfo fileInfo = fileStorageService.of(file)
                .setPath(datePath)
                .setSaveFilename(fileName)
                .upload();

        if (fileInfo == null) {
            throw new ServiceException("上传文件失败");
        }
        return fileInfo.getUrl();
    }

    @Override
    public Boolean delete(String url) {
        final String platform = "tencent-cos-1";
        final String basePath = "ccblog/";
        String fileName = url.substring(url.lastIndexOf("/"));
        String path = url.substring(url.lastIndexOf(basePath)+basePath.length(), url.lastIndexOf("/"));
        FileInfo fileInfo = new FileInfo()
                .setPlatform(platform)
                .setBasePath(basePath)
                .setPath(path)
                .setFilename(fileName);
        return fileStorageService.delete(fileInfo);
    }
}
